import numpy as np
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
from sklearn.manifold import TSNE

# 模拟两个语义相近的句子
sentence_1 = "猫在树上睡觉"
sentence_2 = "猫在阳光下打盹"

# 模拟词嵌入表示（假设每个单词的向量为随机生成）
np.random.seed(42)
word_embeddings = {
    "猫": np.random.rand(5), 
    "在": np.random.rand(5), 
    "树上": np.random.rand(5), 
    "睡觉": np.random.rand(5), 
    "阳光下": np.random.rand(5), 
    "打盹": np.random.rand(5) 
}

# 将句子表示为向量（简单取词向量的平均值）
def sentence_to_vector(sentence, embeddings):
    words = sentence.split(" ")  # 注意：中文句子没有空格，这会导致问题
    vectors = [embeddings[word] for word in words if word in embeddings]
    return np.mean(vectors, axis=0)

vector_1 = sentence_to_vector(sentence_1, word_embeddings)
vector_2 = sentence_to_vector(sentence_2, word_embeddings)

# 确保向量是二维的
vector_1_2d = vector_1.reshape(1, -1)
vector_2_2d = vector_2.reshape(1, -1)

# 计算欧氏距离和余弦相似度
euclidean_dist = euclidean_distances(vector_1_2d, vector_2_2d)[0][0]
cos_sim = cosine_similarity(vector_1_2d, vector_2_2d)[0][0]
print("句子1向量:", vector_1)
print("句子2向量:", vector_2)
print("欧氏距离:", euclidean_dist)
print("余弦相似度:", cos_sim)

# 使用t-SNE可视化嵌入空间（降维到2维）
tsne = TSNE(n_components=2, random_state=42)
low_dim_embeddings = tsne.fit_transform(np.vstack([vector_1, vector_2]))
print("\n降维后的嵌入空间坐标:")
print("句子1:", low_dim_embeddings[0])
print("句子2:", low_dim_embeddings[1])

# 判断相似度计算的误差来源
def analyze_error(vector1, vector2):
    diff = np.abs(vector1 - vector2)
    max_error_dim = np.argmax(diff)
    return max_error_dim, diff[max_error_dim]

error_dim, error_value = analyze_error(vector_1, vector_2)
print("\n最大误差所在维度:", error_dim)
print("误差值:", error_value)